import fs from 'fs';
import path from 'path';
import { compatibilityEngine } from './intelligent-compat';
import { ExecutionMode, ExecutionOptions } from './execution-mode';

type SafeFunction<T> = (...args: any[]) => Promise<T>;

export function withIntelligentCompat<T>(
  fn: SafeFunction<T>,
  options?: ExecutionOptions
): SafeFunction<T> {
  return async (...args) => {
    try {
      return await fn(...args);
    } catch (error) {
      const logPath = path.join(__dirname, '../../logs/compatibility-errors.log');
      const err = error as Error;
      
      fs.writeFileSync(logPath, JSON.stringify({
        timestamp: new Date().toISOString(),
        error: {
          message: err.message,
          stack: err.stack
        },
        context: {
          function: fn.name,
          args,
          options
        }
      }, null, 2));

      const solution = await compatibilityEngine.handleError(
        err,
        { 
          function: fn.name,
          args,
          options
        }
      );

      if (options?.mode === ExecutionMode.INTELLIGENT && solution) {
        console.warn(`[智能兼容] 自动应用修复方案:\n${solution}`);
        // 在实际项目中这里可以自动重试或应用修复
        return fn(...args); // 简化示例，实际应应用具体修复
      }

      throw error;
    }
  };
}

// 示例使用方式：
/*
const safeFetch = withIntelligentCompat(fetch, {
  mode: ExecutionMode.INTELLIGENT
});
*/